package com.cskaoyan.controller.wx;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.common.BaseRespVo;


import org.apache.shiro.session.mgt.eis.SessionDAO;

import com.cskaoyan.config.realm.MarketToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.PostMapping;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author gatsby
 * @since 2022/10/14 12:36
 */
@RestController
@RequestMapping("wx/auth")
public class WxAuthController {

    @RequestMapping("login")
    public BaseRespVo<LoginWxUserData> login(@RequestBody Map map, HttpServletRequest request) {
        String username = (String)map.get("username");
        String password = (String)map.get("password");

        // 写业务
        Subject subject = SecurityUtils.getSubject();
        //UsernamePasswordToken authenticationToken = new UsernamePasswordToken(username,password);
        MarketToken authenticationToken = new MarketToken(username, password, "wx");
        try {
            subject.login(authenticationToken);
        } catch (AuthenticationException e) {
            e.printStackTrace();
        }

        boolean authenticated = subject.isAuthenticated();
        /*if (subject.isAuthenticated()) {
            System.out.println("认证成功");
        }*/

        Session session = subject.getSession();
        MarketUser marketUser = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
        //session.setAttribute("marketUser",marketUser);





        LoginWxUserData loginWxUserData = new LoginWxUserData();
        UserInfoBean userInfo = new UserInfoBean();
        userInfo.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        userInfo.setNickName("user123");
        loginWxUserData.setUserInfo(userInfo);
        // loginUserData.setToken("c4d988f3-e4c5-4e46-b6ce-13b9e008ea20");
        loginWxUserData.setToken((String)session.getId());
        return BaseRespVo.ok(loginWxUserData);
    }

    @PostMapping("logout")
    public BaseRespVo logout() {
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.logout();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return BaseRespVo.ok();
    }
}
